﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WLive
{
    public class Connection
    {
        static DateTime m_token_expires_date;

        static bool expired = true;

        public string token_type;
        public string scope;
        public static string refresh_token;
        public string authentication_token;
        public string access_token;
        public static string client_id;
        public static string client_secret;
        public static string redirect_uri;
        public static string code;
        public static string grant_type;
        public static string refreshtoken;

        public static string url = "https://login.live.com/oauth20_token.srf";

        static Connection connection;
        
        public static string Token
        {
            get
            {
                if (DateTime.Now > m_token_expires_date)
                {
                    expired = true;
                    do
                    {
                        if (Expired != null)
                            Expired(null, new EventArgs());
                    } while (expired);
                }
                return connection.access_token;
            }
        }
        
        public string expires_in
        {
            set
            {
                m_token_expires_date = DateTime.Now.AddSeconds(double.Parse(value) - 10);
                expired = false;
            }
        }

        public delegate void OnExpired(object sender, EventArgs e);
        /// <summary>
        /// Event is raised when access token expired
        /// </summary>
        public static event OnExpired Expired;
        /// <summary>
        /// Gives new access token. Use this method for login or refreshing access token
        /// </summary>
        public static void Login()
        {
            
            QueryParameters qp = new QueryParameters();
            if (!string.IsNullOrEmpty(Connection.refresh_token))
            {
                qp.Add("refresh_token", Connection.refresh_token);
                grant_type = "refresh_token";
            }
            else
            {
                qp.Add("code", code);
                grant_type = "authorization_code";
            }
            qp.Add("grant_type", grant_type);
            qp.Add("client_id", client_id);
            qp.Add("client_secret", client_secret);
            qp.Add("redirect_uri", redirect_uri);
            string url = UrlBuilder1.Concat("https://login.live.com/oauth20_token.srf", qp);
            try
            {
                connection = Requester.Request<Connection>(new RequestObject { url = url }).ElementAt(0);
            }
            catch (Exception e)
            { throw e; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="scopes">Scopes which you want to use</param>
        /// <param name="response_type">Access token, code, ...</param>
        /// <param name="isMobileApps">True when your app is mobile otherwise false</param>
        /// <returns>Returns Url for authorization</returns>
        public static string GetAuthorizationUrl(string[] scopes, string response_type, bool isMobileApps = false)
        {
            QueryParameters qp = new QueryParameters();
            string ret = "";
            foreach (string s in scopes)
                ret += s + ",";
            if (ret.EndsWith(","))
                ret = ret.Substring(0, ret.Length - 1);
            qp.Add("scope", ret);
            qp.Add("response_type", response_type);
            if (isMobileApps)
                qp.Add("display", "touch");
            qp.Add("client_id", client_id);
            qp.Add("client_secret", client_secret);
            qp.Add("redirect_uri", redirect_uri);
            return UrlBuilder1.Concat("https://login.live.com/oauth20_authorize.srf", qp);
            //return "https://login.live.com/oauth20_authorize.srf?" + UrlBuilder.Url(new Connection(), "auth_url", values);
        }
        /// <summary>
        /// Logout user
        /// </summary>
        public static void Logout()
        { }
    }
}
